#!/usr/bin/env node
/*
 * @Description: 自动打开小程序的配置
 * @Author: yilingsj（315800015@qq.com）
 * @Date: 2021-05-01 10:14:14
 * @LastEditors: yiling (315800015@qq.com)
 * @LastEditTime: 2021-05-20 18:10:21
 */
const shell = require('shelljs')
const path = require('path')
const utils = require('./utils')
const GLOBAL_CONFIG = require('../src/config')
const config = require('./config')
const WEIXIN_DEVTOOLS_PATH = config.weixin.path // 获取微信开发者工具安装路径

// 运行项目路径读取
const PRESET_PATH = path.resolve(__dirname, '../')

// 当前运行环境变量与运行命令
const NODE_ENV = process.env.NODE_ENV
const OUTPUT_PATH = process.env.outputPath || 'dev'
const UNI_PLATFORM = process.env.UNI_PLATFORM
console.log('program.minimize=', ';process.env.NODE_ENV=', process.env.NODE_ENV, ';process.env.=', OUTPUT_PATH)
// console.log('NODE_ENV',NODE_ENV,';UNI_PLATFORM=',UNI_PLATFORM)

// 微信项目源码路径
const WEIXIN_PROJECT_PATH = `dist/${OUTPUT_PATH}/mp-weixin`
const WEIXIN_PRESET_PATH = path.resolve(PRESET_PATH, WEIXIN_PROJECT_PATH)
const EXEC_CODE = utils.getRunPresetExec(NODE_ENV, UNI_PLATFORM, WEIXIN_PROJECT_PATH)
const PROJECT = path.resolve(WEIXIN_PRESET_PATH, './project.config.json')
const APP_JSON = path.resolve(WEIXIN_PRESET_PATH, './app.json')

if (!WEIXIN_DEVTOOLS_PATH) {
  shell.echo('没有找到微信开发者工具安装路径，请检查配置项！')
  shell.exit()
}
shell.cd(PRESET_PATH)
var childProcess = shell.exec(EXEC_CODE, { async: true })
// 监听回调
childProcess.stdout.on('data', function (data) {
  if (data.match('Build complete')) {
    console.log('成功', Date.now())
    if (shell.cd(WEIXIN_DEVTOOLS_PATH)) {
      utils.findProjectConfig(PROJECT, GLOBAL_CONFIG, WEIXIN_PRESET_PATH, APP_JSON)
    } else {
      shell.echo('微信开发者工具安装路径异常，请检查配置项！')
      shell.exit()
    }
  }
})

childProcess.stderr.on('data', function (data) {
  console.log('stderr: ' + data)
})
